/*
 * @description 管理员的数据访问对象
 * @Author: Eve 
 * @Date: 2021-09-09 15:24:45 
 * @Last Modified by: Eve
 * @Last Modified time: 2021-09-10 17:58:55
 */
const { Admin } = require('../models/admin')
const bcrypt = require('bcryptjs')
//const gensalt = bcrypt.genSaltSync(10)
class AdminController {
  // 创建管理员
  static async create(params) {
    const { email, password, username } = params
    const hasAdmin = await Admin.findOne({
      where: {
        email,
        deleted_at: null
      }
    });
    if (hasAdmin) {
      throw new global.errs.Existing('管理员已存在');
    }
    const admin = new Admin();
    admin.username = username
    admin.email = email
  //  admin.password =  bcrypt.hashSync(password, gensalt)
  admin.password = password
    admin.save()
    return {
      email: admin.email,
      username: admin.username
    }

  }
  //登录验证密码
  static async verify(email, plainPassword) {
    
    // 查询用户是否存在
    const admin = await Admin.findOne({
      where: {
        email
      }
    })

    if (!admin) {
      throw new global.errs.AuthFailed('账号不存在')
    }
    // 验证密码是否正确
  //  const pw =  bcrypt.hashSync(plainPassword, gensalt)
   
  //  const correct = bcrypt.compareSync(pw, admin.password);

    if (plainPassword != admin.password) {
      throw new global.errs.AuthFailed('密码不正确')
    }
    return admin
  }

  // 用户列表
  static async list() {
    return await Admin.findAll({
      raw: true
    });
  }

}

module.exports = {
  AdminController
}
